package org.jeecg.modules.mall.service.impl;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkCouponGetRequest;
import com.taobao.api.request.TbkDgMaterialOptionalRequest;
import com.taobao.api.request.TbkTpwdCreateRequest;
import com.taobao.api.response.TbkCouponGetResponse;
import com.taobao.api.response.TbkDgMaterialOptionalResponse;
import com.taobao.api.response.TbkTpwdCreateResponse;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.mall.BeanMapperUtil;
import org.jeecg.common.util.mall.HttpUtils;
import org.jeecg.modules.mall.entity.TbMnCatItem;
import org.jeecg.modules.mall.entity.TbMnMaterialOptional;
import org.jeecg.modules.mall.service.IDtkManager;
import org.jeecg.modules.mall.service.ITbMnCatItemService;
import org.jeecg.modules.mall.service.ITbMnMaterialOptionalService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import static org.jeecg.modules.mall.service.impl.Contents.appkey;

/**
 * <p>
 * 描述
 * </p>
 * 9/29
 */
@Service
@Slf4j
public class DtkManagerImpl implements IDtkManager {

    @Autowired
    private ITbMnCatItemService tbMnCatItemService;

    @Autowired
    private ITbMnMaterialOptionalService tbMnMaterialOptionalService;

    /**
     * 业务入口
     */
    public void execute() throws ApiException {
        log.info("获取所有商品类目名称");
        QueryWrapper  tbMnCatItemQueryWrapper=new QueryWrapper();
        tbMnCatItemQueryWrapper.eq("state","1");
        List<TbMnCatItem> tbMnCatItemList = tbMnCatItemService.list(tbMnCatItemQueryWrapper);
        //获取前15页的数据
        for(int i = 0 ; i < 1 ; i++){
            for(TbMnCatItem tbMnCatItem : tbMnCatItemList){
                //http://www.dataoke.com/qlist/?keywords=%E8%A1%AC%E8%A1%AB&cid=1&px=sell&page=2
             //   String cid = getCid(tbMnCatItem);
                String cid = tbMnCatItem.getCatId();
                String url = Contents.DAK_URL+"?keywords="+tbMnCatItem.getCategoryName()+"&cid="+cid+"&xuan=keyword&page="+i+"&px=sell";
                Document doc = null;
                try {

                    String rsp = HttpUtils.httpClientGet(url,"");
                    doc = Jsoup.parse(rsp);
                } catch (Exception e) {
                    continue;
                }
                Elements rows = doc.getElementsByClass("goods-item");
                for(int j = 0 ; j<rows.size() ; j++){
                    //获取商品id
                    String numIid = rows.get(j).attr("data_goodsid");
                    //判断商品是否已经存在
                    QueryWrapper tbmnMaterialoptionalQueryWrapper=new QueryWrapper();
                    tbmnMaterialoptionalQueryWrapper.eq("num_iid",Long.valueOf(numIid));
                    List<TbMnMaterialOptional> list = tbMnMaterialOptionalService.list(tbmnMaterialoptionalQueryWrapper);
                    if(list.size() > 0) continue;

                    String itemUrl = "https://detail.tmall.com/item.htm?id="+numIid;
                    //通过物料搜索接口获取优惠券信息
                    TaobaoClient client = new DefaultTaobaoClient(Contents.MATERIAL_OPTIONAL_URL, Contents.appkey, Contents.secret);
                    TbkDgMaterialOptionalRequest req = new TbkDgMaterialOptionalRequest();
                    req.setQ(itemUrl);
                    req.setAdzoneId(Contents.adzone_id);
                    TbkDgMaterialOptionalResponse.MapData mapData = null;
                    String command = null;
                    String couponAmonunt = null;
                    String smallImages = null;
                    try {
                        TbkDgMaterialOptionalResponse optionalResponse = client.execute(req);
                        mapData = optionalResponse.getResultList().get(0);
                        //如果券有效期为空，则continue
                        if(null == mapData.getCouponStartTime()) continue;
                        //获取淘口令
                        command = getCommand(mapData);
                        if(null == command || "" == command) continue;
                        //获取优惠券金额
                        couponAmonunt = getCouponAmount(mapData);
                        smallImages = getSmallImages(mapData.getSmallImages());

                        //获取详情页的商品推荐语
                        String datagId = rows.get(j).attr("id").replace("goods-items_","");
                        String rsp1 = HttpUtils.httpClientGet("http://www.dataoke.com/item?id="+datagId,"");
                        Document doc1 = Jsoup.parse(rsp1);
                        //获得所有p标签
                        //Elements links = doc1.select("div.goods-info div.goods-tit > p");
                        Elements links = doc1.select("div.msg-block").select("p.top-des");
                        String tuiJianYu = links.get(0).text();

                        TbMnMaterialOptional record = BeanMapperUtil.objConvert(mapData,TbMnMaterialOptional.class);
                        record.setLevelOneCategoryId(Long.valueOf(tbMnCatItem.getCatId()));
                        record.setCategoryId(Long.valueOf(tbMnCatItem.getCategoryId()));
                        record.setTokenTime(DateUtil.formatDate(new Date()));
                        record.setToken(command);
                        record.setSmallImages(smallImages);
                        record.setCouponAmount(couponAmonunt);
                        record.setJddPrice(tuiJianYu);
                        tbMnMaterialOptionalService.save(record);
                    } catch (Exception e) {
                        continue;
                    }
                }
            }
        }
    }


    public String getCouponAmount(TbkDgMaterialOptionalResponse.MapData mapData) throws ApiException {
        TaobaoClient client = new DefaultTaobaoClient(Contents.MATERIAL_OPTIONAL_URL, Contents.appkey, Contents.secret);
        TbkCouponGetRequest req = new TbkCouponGetRequest();
        req.setItemId(mapData.getNumIid());
        req.setActivityId(mapData.getCouponId());
        TbkCouponGetResponse rsp = client.execute(req);
        TbkCouponGetResponse.MapData mapData1 = rsp.getData();
        return mapData1.getCouponAmount();
    }

    public void Test(){
            TaobaoClient client = new DefaultTaobaoClient(Contents.MATERIAL_OPTIONAL_URL, Contents.appkey, Contents.secret);
//         TbkScAdzoneCreateRequest req = new TbkScAdzoneCreateRequest();
//            req.setSiteId(29420098l);
//            req.setAdzoneName("广告位");
//            TbkScAdzoneCreateResponse rsp = client.execute(req, sessionKey);
//            System.out.println(rsp.getBody());



    }

    private String getSmallImages(List<String> list) {
        StringBuffer sb = new StringBuffer();
        for(String str : list){
            sb.append(str);
            sb.append(",");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    /**
     * 生成淘口令
     * @param mapData
     * @return
     */
    public String getCommand(TbkDgMaterialOptionalResponse.MapData mapData) {
        String tbkCode="";
        try {
            TaobaoClient client = new DefaultTaobaoClient(Contents.MATERIAL_OPTIONAL_URL, Contents.appkey, Contents.secret);
            TbkTpwdCreateRequest req = new TbkTpwdCreateRequest();
            req.setText(mapData.getTitle());
            if(null != mapData.getCouponEndTime()){
                req.setUrl("https:"+mapData.getCouponShareUrl());
            }else {
                req.setUrl("https:"+mapData.getUrl());
            }
            req.setLogo(mapData.getPictUrl());
            TbkTpwdCreateResponse rsp = client.execute(req);
            if("" == rsp.getErrorCode()){
                tbkCode = rsp.getData().getModel();
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return tbkCode;
    }
}
